import React,{Component} from 'react';
import { Icon, Input, Button, Table, Pagination, message } from 'antd';
import { Link } from 'react-router-dom';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
import Bread from '../common/Bread/index';
import Join from './Join'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'


const Search = Input.Search;

class accountService extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			data: [],
			markClass: localStorage.getItem('markStatus') ? 'mark markClass': 'mark',
			page:['10','20','30','40','50','60','70','80','90'],
			page_1: 1,
			limit: 10,
			oldMobile: '',
			realName: '',
			JoinVisible: false,
		}
	}
	columns = [{
		title: '组织名称',
		dataIndex: '组织名称',
		key: '组织名称',
	  }, {
		title: '身份',
		dataIndex: '身份',
		key: '身份',
	  }, {
		title: '加入时间',
		dataIndex: '加入时间',
		key: '加入时间',
	}];
	onShowSizeChange=(current, pageSize)=> {
		// console.log(current, pageSize);
		this.getData(current, pageSize);
		this.setState({
			limit: pageSize
		})
	}
	onChange=(pageNumber)=> {
	  // console.log('Page: ', pageNumber);
	  this.getData(pageNumber);
	}
	
	handleClickMark = ()=>{
		localStorage.setItem('markStatus',true);
		this.setState({
			markClass: localStorage.getItem('markStatus') ? 'mark markClass': 'mark',
		})
	}
	getData= (page,limit=this.state.limit)=>{
		const _this = this;
		const Token = localStorage.getItem("token");
		axios({
			method: 'get',
			url: '/api/customer/baasorg/org/all',
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			},
			params: {
				page: page,
				limit: limit
			}
		})
		.then(function (response) {
			// console.log(response);
			let data = [];
			response.data&&response.data.data&&response.data.data.rows&&response.data.data.rows.forEach((e,i)=>{
				if(e.leaderStatus == 0){
					e.leaderStatus = '组织者'
				}else {
					e.leaderStatus = '用户'
				}
				data.push({
					key: i+'',
					"组织名称": e.orgName,
					"身份": e.leaderStatus,
					"加入时间": e.createTime,
				})
			})
			_this.setState({
				data: data,
				totalnum: response.data.data.total,
			})
		})
		.catch(function (error) {
			console.log(error)
		});
		
	}	
	JoinModal =()=>{
		this.setState({
			JoinVisible: true
		})
		const _this = this;
		const Token = localStorage.getItem("token");
		axios({
		  method: 'get',
		  url: '/api/customer/user/getUser',
		  headers: {
		    'Content-Type': 'application/json',
		    Authorization:Token,
		  }
		})
		.then(function(response){
		  const data = response.data.data;
		  if(response.data.code == '200'){
		    _this.setState({
		        oldMobile: data.telPhone,
		        realName: data.name
		    })
		  }
		})
		.catch(function(error){
		  message.error('获取手机号失败')
		})
		
	}
	JoinCancel =()=>{
		this.setState({
			JoinVisible: false
		})
	}
	componentWillMount(){
		this.getData(this.state.page_1,this.state.limit);
		const Token = localStorage.getItem("token");
		axios({
			method: 'get',
			url: '/api/customer/user/queryUserOrg',
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
		})
		.then(function(response){
			if(response.data.data == 1){
				localStorage.setItem("queryUserOrg", 1);
			}else {
				localStorage.setItem("queryUserOrg", 0);
			}
		})
		.catch(function(error){
			console.log('请求失败，请稍后再试！')
		})
	}

	handleSubmit = (_this)=>{
		// console.log(_this)
		const $this = this;
		const phone = this.state.oldMobile;
		const Token = localStorage.getItem("token");
		_this.props.form.validateFields((err, values) => {
			if(!err){
				var data = {
					code: values.code,
					telPhone: phone,
					reason: values.reason,
				}
				axios({
					method: 'get',
					url: '/api/customer/rest/checkMsg?mobile='+ phone +'&code='+ values.yzmCode,
	                headers: {
	                  'Content-Type': 'application/json',
	                  Authorization: Token,
                	}
                })	
                .then(function(response){
                	if(response.data.data == 'error'){
                		 message.warning('请输入正确的验证码');
                	}else if(response.data.data == 'success'){
                		axios({
                			method:'post',
                			url: '/api/customer/user/approval/join/'+ values.code,
                			data: data,
                			headers: {
                				'Content-Type': 'application/json',
                				Authorization:Token,
                			}
                		})
                		.then(function (response) {
                			if(response.data.code == 201){
                				message.warning('重复加入');
                				_this.props.form.resetFields();
                			}else if(response.data.code == 202){
                				message.warning('邀请码错误');
                			}else if(response.data.code == 203){
                				message.warning('重复申请');
                				_this.props.form.resetFields();
                			}else if(response.data.code == 200){
                				message.success('已申请加入 请等待管理员审核');
                				_this.props.form.resetFields();
                				$this.setState({
                					JoinVisible: false
                				})
                				// _this.props.history.push('/accountService/Toexamine');
                			}else{
                				message.warning('操作失败');
                			}
                			// console.log(response)
                		})
                		.catch(function (error) {
                			console.log(error);
                		});
                	}	
                })	
			}else {
				console.log('Received values of form: ', values);
			}
		})
	}

	render() {
		const disabled = (localStorage.getItem('sandbox') == 0) || (localStorage.getItem('queryUserOrg') == 1) ? 'creatBtn hide': 'creatBtn';
		return (
				<div>
					<Bread bread={['组织管理',['组织管理','accountService']]}/>
					<div>
						<div className="index-buttons">
							<Link to="/accountService/CreateOrganization"><Button type="primary" className={disabled} style={{ marginRight: 10 }}>新建一个组织</Button></Link>
							<Button type="Default" onClick = {this.JoinModal}>加入一个组织</Button>
							<Link to="/accountService/UserList"><Button type="Default" style={{ marginLeft: 10 }}>管理我创建的组织</Button></Link>
						</div>
						<Table 
						columns={this.columns} 
						dataSource={this.state.data} 
						bordered
						pagination={false} />
						<div className="page_foot">
							<span className="data_num">共{this.state.totalnum}条</span>
							<Pagination 
								pageSizeOptions={this.state.page} 
								className="page" 
								showSizeChanger 
								showQuickJumper
								onShowSizeChange={this.onShowSizeChange} 
								defaultCurrent={1} 
								total={this.state.totalnum} 
								onChange={this.onChange} />
						</div>
					</div>
					{/*<div className = {this.state.markClass}>
						<img src={require('./img/guidance.png')} alt="" onClick = {this.handleClickMark} />
	                </div>*/}
	                <Join 
						visible = {this.state.JoinVisible}
						onCancel = {this.JoinCancel}
						oldMobile = {this.state.oldMobile}
						realName = {this.state.realName}
						onModalOk = {this.handleSubmit}
					 />
				</div>
					
		);
	}
}

// export default accountService;
export default connect((state) => {
	return { ...state };
})(accountService);